import {
  fetchUserCenter
} from '../../services/usercenter/fetchUsercenter';
import Toast from '/tdesign-miniprogram/toast/index';
import {
  users
} from '../../tools/users'
import {
  msg
} from '../../tools/msg'
import {
  rsa
} from '../../tools/rsa'
import {
  OrderStatus,
  orderTagInfos
} from '../../pages/order/config'
import {
  ds
} from '../../tools/data';
import {
  pay
} from '../../tools/pay';
import {
  ui
} from '../../tools/ui';
import {
  exTool
} from './exTicket/exTool';
import {
  shops
} from '../../tools/shops';
import {
  menuData
} from './menus';
import {
  nav2
} from '../../tools/nav2';
import {
  adv
} from '../../tools/adv'

Page({
  data: {
    showMakePhone: false,
    userInfo: { // personInfo
      avatarUrl: '',
      nickName: '正在登录...',
      phoneNumber: '',
    },
    userInfoEx: {}, // user
    user: {},
    menuData,
    orderTagInfos,
    customerServiceInfo: {},
    currAuthStep: 1,
    showKefu: true,
    versionNo: '',
    addr: {},
    mainSwitch: false,
    newMsgCount: 0,
    couponNum: -1,
    ticketNum: -1
  },
  onLoad() {
    this.getVersionInfo();
  },
  onShow() { // 获取用户信息
    this.getTabBar().init(4);
    this.init();

    users.getUserInfo()
      .then(async res => {
        this.setData({
          user: res,
          userInfo: res.personInfo || {},
          userInfoEx: res,
          currAuthStep: 2
        })
        this.countTicket()
      });

    this.countOrders()
    this.loadAddr()
    this.setupNotify()
    this.loadCoupons()
  },
  loadCoupons() {
    const compo = this.selectComponent("#list-coupons")
    compo.coupons()
      .then(res => {
        console.log(res)
        const coupons = res.couponResultList || [],
          now = Date.now()
        let warnNum = 0
        coupons.forEach(ele => {
          const end = ele.source.end || 0,
            diffDay = (end - now) / 1000 / 3600 / 24
          if (end && diffDay > 0 && diffDay <= 7) warnNum += 1
        })
        this.setData({
          couponNum: coupons.length ?? 0,
          warnNum
        })
      })
      .catch(err => {
        console.error(err)
        this.setData({
          couponNum: 0
        })
      })
  },
  countTicket() {
    const {
      user
    } = this.data

    ds.coll('orders')
      .aggregate()
      .match({
        _openid: user._openid,
        payStatus: 'success',
        $expr: {
          $gt: ["$ticketInfo.totalAmount", "$ticketInfo.used"]
        }
      })
      .group({
        _id: 0, // 所有记录合并为一组
        ticketNum: {
          $sum: {
            $subtract: ["$ticketInfo.totalAmount", "$ticketInfo.used"]
          }
        }
      })
      .end()
      .then(res => {
        this.setData({
          ticketNum: res.list[0]?.ticketNum ?? 0
        })
      })
      .catch(res => {
        console.error(res)
        this.setData({
          ticketNum: 0
        })
      })
  },
  // peekNewMsg(user) {
  //   // console.log(user)
  //   wx.cloud.callFunction({
  //     name: 'chatCmd',
  //     data: {
  //       cmd: 'peekNewMsg',
  //       userId: user._id,
  //       userOpenId: user._openid,
  //       userRole: user.role,
  //     }
  //   }).then(res => {
  //     this.setData({
  //       newMsgCount: Math.min(res.result.totalNewMsgCount, 99)
  //     })
  //   })
  // },
  loadAddr() {
    ds.cloudGetByOpenid('delivery_addr', res => {
      // console.log(res)
      const addr = res.result.data[0]
      this.setData({
        addr
      })
    })
  },
  // 订单分类计数
  countOrders() {
    ds.cloudGetByOpenid('orders', res => {
      // console.log(res)
      const orders = res.result.data
      const tests = [{
        title: '待付款',
        fn: order => {
          return order.payStatus == 'wait'
        }
      }, {
        title: '待配送'
      }, {
        title: '配送中'
      }, ]
      orders.forEach(order => {
        if (order.ticketInfo) return
        tests.forEach(test => {
          const fn = test.fn || (order => {
            return order.status == test.title
          })
          if (fn(order)) test.count = (test.count || 0) + 1
        })
      })
      // console.log(tests) 
      const orderTagInfos = this.data.orderTagInfos
      orderTagInfos.forEach(ele => {
        tests.forEach(test => {
          if (test.title == ele.title) ele.orderNum = test.count || 0
        })
      })
      this.setData({
        orderTagInfos
      })
    })
  },
  setupNotify() {
    wx.getSetting({
        withSubscriptions: true,
      })
      .then(res => {
        const {
          mainSwitch
        } = res.subscriptionsSetting
        this.setData({
          mainSwitch
        })
      })
  },
  onPullDownRefresh() {
    this.init();
  },
  init() {
    this.fetUseriInfoHandle();
  },

  fetUseriInfoHandle() {
    return;
    fetchUserCenter().then(
      ({
        userInfo,
        countsData,
        orderTagInfos: orderInfo,
        customerServiceInfo,
      }) => {
        // eslint-disable-next-line no-unused-expressions
        menuData?.[0].forEach((v) => {
          countsData.forEach((counts) => {
            if (counts.type === v.type) {
              // eslint-disable-next-line no-param-reassign
              v.tit = counts.num;
            }
          });
        });
        const info = orderTagInfos.map((v, index) => ({
          ...v,
          ...orderInfo[index],
        }));
        this.setData({
          userInfo,
          menuData,
          orderTagInfos: info,
          customerServiceInfo,
          currAuthStep: 2,
        });
        wx.stopPullDownRefresh();
      },
    );
  },
  onTestClick() {
    wx.navigateTo({
      url: '/pages/test/test',
    })
  },
  onClickCell({ // 点击各条目
    currentTarget
  }) {
    const {
      user
    } = this.data
    const {
      type
    } = currentTarget.dataset;
    const {
      url, // title, type
    } = currentTarget.dataset.item
    const that = this
    switch (type) {
      case 'scan': {
        wx.scanCode({
          onlyFromCamera: true, // 只允许从相机扫码
          success(res) {
            // console.log(that.data.user, that.data.userInfo)
            that.execScanQr(res.result)
          }
        })
        break
      }
      case 'service': {
        this.openMakePhone();
        break;
      }
      case 'help-center': {
        this.nav2Chat()
        break;
      }
      case 'point': {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '你点击了积分菜单',
          icon: '',
          duration: 1000,
        });
        break;
      }
      case 'msg': {
        // 允许消息提醒
        msg.request(res => {
          const accept = (Object.values(res)[0] == 'accept')
          if (!accept) return
          this.setupNotify()
        })
        break
      }
      case 'myqr': {
        const param = JSON.stringify({
          title: '我的用户码',
          nickName: user.personInfo?.nickName || ''
        })
        const ex = rsa.encrypt(JSON.stringify({
          userId: user._id
        }))
        // console.log(param, ex)
        wx.navigateTo({
          url: `/pages/qr/qrcode?param=${param}&ex=${ex}`,
        })
        break
      }
      case 'offlinePay': {
        wx.navigateTo({
          url: `/pages/showqr/showqr?title=空桶押金&userOpenId=${user._openid}`,
        })
        break
      }
      default: {
        if (url) {
          wx.navigateTo({
            url
          })
          break
        }
        Toast({
          context: this,
          selector: '#t-toast',
          message: '未知跳转',
          icon: '',
          duration: 1000,
        });
        break;
      }
    }
  },
  async nav2Chat() {
    const user = this.data.user
    const url = ['admin', 'master', ].indexOf(user.role) >= 0 ? '/pages/chat/list/chatlist' : `/pages/chat/chat?sessionOpenId=${user._openid}`
    wx.navigateTo({
      url
    })
  },
  gotoQr(paramObj, exObj) {
    const param = JSON.stringify(paramObj)
    const ex = rsa.encrypt(JSON.stringify(exObj))
    // console.log(param, ex)
    wx.navigateTo({
      url: `/pages/qr/qrcode?param=${param}&ex=${ex}`,
    })
  },
  // 扫码后执行
  execScanQr(result) {
    const obj = JSON.parse(result)
    obj.userOpenId = this.data.user._openid
    const {
      title,
      fee,
      barrel, // 空桶押金
      userOpenId, // 空桶押金
      orderId, // 步梯费
      staffOpenId, // 推广
      nickName, // 推广
    } = obj

    // console.log(obj)
    if (title == '空桶押金') {
      this.payBarrelPladge(obj)
    } else if (title == '步梯费') {
      pay.qrPay(obj, res => {
        // console.log(res)
        ui.toast(res.status == 'success')
      })
    } else if (title == '推广') {
      ui.confirm(`确定与${nickName}进行销售绑定吗？`, async res => {
        if (!res) return
        // this.bindStaff(staffOpenId)
        res = await adv.bind(this.data.user._openid, staffOpenId)
        ui.toast(res.success, res.msg)
      })
    } else if (title == '兑换码') {
      exTool.exchange(this.data.user, obj)
    }
  },
  payBarrelPladge(dataObj) {
    pay.qrPay(dataObj, res => {
      ui.toast(res.status == 'success')
    })
  },
  bindStaff(staffOpenId) { // 推广绑定 -> adv.bind()
    ds.cloudGetByOpenid('users', res => {
      const user = res.result.data[0]
      if (user.bind) {
        ui.toast(false, '您已存在绑定')
        return
      }
      ds.cloudUpdateWhere('users', {
        _id: user._id
      }, {
        bind: staffOpenId,
        bindTime: new Date().getTime()
      }, res => {
        // console.log(res)
        ui.toast(res.result.errMsg.endsWith(':ok'))
      })
    })
  },
  // 待付款，配送中，已送达
  jumpNav(e) {
    const status = e.detail.status;
    // console.log(e)
    if (status === 0) {
      wx.navigateTo({
        url: '/pages/order/after-service-list/index'
      });
      return
    }

    const ticketParam = (status == -2 ? '&ticket=true' : '')
    if (status == -2) status == -1
    wx.navigateTo({
      url: `/pages/order/order-list/index?status=${status}${ticketParam}`
    });

  },
  // 全部订单
  jumpAllOrder() {
    wx.navigateTo({
      url: '/pages/order/order-list/index?status=-1'
    });
  },

  async openMakePhone() {
    // this.setData({
    //   showMakePhone: true
    // });
    ui.loading()
    const actions = {}
    const ids = shops.getShopList().map(ele => {
      return ele.id
    })
    // console.log(ids)
    const userRes = await ds.coll('users')
      .where({
        role: ds.cmd.eq('master'),
        shop: {
          id: ds.cmd.in(ids)
        }
      })
      .get()
    const users = userRes.data
    // console.log(users)
    users.forEach(user => {
      if (user.phoneNumber) {
        actions[user.phoneNumber] = user.shop.name
      }
    })

    ui.loading(false)

    ui.actionSheet(actions, (value, key) => {
      wx.makePhoneCall({
        phoneNumber: key,
      })
    })
  },

  closeMakePhone() {
    this.setData({
      showMakePhone: false
    });
  },

  call() {
    wx.makePhoneCall({
      phoneNumber: this.data.customerServiceInfo.servicePhone,
    });
  },

  gotoUserEditPage() {
    // if (!this.data.userInfo.avatarUrl) {
    //   return users.getProfile(res => {
    //     // console.log(res)
    //     this.gotoPersonInfoPage()
    //   })
    // }

    this.gotoPersonInfoPage()

    // let {
    //   currAuthStep
    // } = this.data;
    // if (currAuthStep === 2) {
    //   this.gotoPersonInfoPage()
    // } else {
    //   this.fetUseriInfoHandle();
    // }
  },
  gotoPersonInfoPage() {
    wx.navigateTo({
      url: '/pages/usercenter/person-info/index'
    });
  },
  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const {
      version,
      envVersion = __wxConfig
    } = versionInfo.miniProgram;

    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },
  onDevTap() {
    nav2.developer()
  },
  onTicketTap() {
    wx.navigateTo({
      url: '/pages/order/order-list/index?status=-2&ticket=true'
    })
  },
  openCouponTap() {
    ui.loading(true, '加载优惠券')
    this.setData({
      couponsShow: true,
    })
  }
  // onDeliveryFeeTap() {
  //   wx.navigateTo({
  //     url: '/pages/usercenter/staff/index?role=delivery',
  //   })
  // },
  // onSaleSttsTap() {
  //   wx.navigateTo({
  //     url: '/pages/order/statistics/sale/sale-statistics',
  //   })
  // },
  // onDeliverySttsTap() {
  //   wx.navigateTo({
  //     url: '/pages/order/statistics/delivery/delivery-statistics',
  //   })
  // }
});